package com.idea.easy.log.listener;

import com.idea.easy.log.model.CustomLog;
import com.idea.easy.log.provider.EasyLogInfoUtil;
import com.idea.easy.log.provider.EasyLogServerInfoProvider;
import com.idea.easy.log.event.CustomLogEvent;
import com.idea.easy.log.model.CustomLogModel;
import com.idea.easy.log.props.EasyLogProperties;
import com.idea.easy.log.provider.SpringAware;
import com.idea.easy.log.service.mp.ICustomLogService;
import com.idea.easy.log.service.IEasyLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.Assert;

/**
 * @className: CustomLogListener
 * @description: 自定义日志事件的监听
 * @author: salad
 * @date: 2022/6/9
 **/
@Slf4j
@AllArgsConstructor
public class CustomLogListener{

    private final EasyLogProperties properties;

    private final EasyLogServerInfoProvider serverInfoProvider;

    @Async
    @EventListener(CustomLogEvent.class)
    public void listener(CustomLogEvent event) {
        CustomLogModel customLogModel = (CustomLogModel)event.getSource();
        //向实体类中增加额外的信息
        EasyLogInfoUtil.appendServerInfo(customLogModel, serverInfoProvider, properties);
        //向IOC容器中寻找Bean
        ICustomLogService customLogService = SpringAware.getBean(ICustomLogService.class);
        if (customLogService != null){
            CustomLog customLog = new CustomLog();
            BeanUtils.copyProperties(customLogModel,customLog);
            customLog.setLogId(customLogModel.getLogId());
            customLog.setLogData(customLogModel.getLogData())
                    .setLogLevel(customLogModel.getLogLevel());
            customLogService.saveCustomLog(customLog);
        } else {
            IEasyLogService easyLogService = SpringAware.getBean(IEasyLogService.class);
            Assert.notNull(easyLogService,"easy-log: 为了存储日志数据,需要实现 ICustomLogService 或者 IEasyLogService 接口");
            easyLogService.saveCustomLog(customLogModel);
        }
    }

}